package com.qf.controller;

import com.qf.service.UserService;
import com.qf.service.UserServiceImpl;
import com.qf.utils.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取前端传入的参数。
        String uname = request.getParameter("username");
        String pwd = request.getParameter("password");

        if(MyUtil.isEmpty(uname) || MyUtil.isEmpty(pwd)){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }

        UserService service = new UserServiceImpl();
        boolean result = service.login(uname,pwd);

        HttpSession session = request.getSession();

        if(result){
            session.setAttribute("uname", uname);
            response.sendRedirect(request.getContextPath()+"/recordList.jsp");
        }else{
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
